import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, EventEmitter, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { Subject } from 'rxjs';
import { DgControl } from '@farris/designer-services';
import { NotifyService } from '@farris/ui-notify';
import { MessagerService } from '@farris/ui-messager';

@Component({
    selector: 'component-template-manage',
    templateUrl: './component-template-manage.component.html',
    styleUrls: ['./component-template-manage.component.css']
})
export class ComponentTemplateManageComponent implements OnInit {

    /**
     * 关闭按钮事件
    */
    @Output() closeModal = new EventEmitter<any>();
    /**
     * 确定按钮事件
     */
    @Output() submitModal = new EventEmitter<any>();

    /**
     * 绑定编辑器页尾组件
     */
    @ViewChild('footer') modalFooter: TemplateRef<any>;
    /**
     * 编辑器默认弹出窗口显示属性
     */
    public modalConfig = {
        title: '维护组件模板',
        width: 600,
        height: 500,
        showButtons: true,
        resizable: false,
        showMaxButton: false
    };

    templateItems = [];

    selectedItemIds = [];

    /** 模板保存、查询的url地址 */
    private templateUrl = '/api/dev/formdesigner/v1.0/field-template';

    private headerOption = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };

    constructor(private http: HttpClient,
        private notifyService: NotifyService,
        private msgService: MessagerService) { }

    ngOnInit() {
        this.getComponentTemplates().subscribe(data => {
            if (data) {
                this.templateItems = data;
            }
        });
    }

    /**
     * 获取定制模板
     */
    private getComponentTemplates() {

        const subject = new Subject<any>();

        this.http.get(this.templateUrl, this.headerOption).subscribe((templates: any[]) => {
            if (!templates || !templates.length) {
                subject.next(null);
                return;
            }
            const items = [];

            templates.forEach((template: any) => {
                if (template && template.templateDom) {
                    const templateDom = JSON.parse(template.templateDom);
                    const templateControlType = templateDom.type;
                    const source = template.templateSource ? JSON.parse(template.templateSource) : null;
                    const item = {
                        id: template.id,
                        name: template.name,
                        type: templateControlType,
                        controlIconClass: '',
                        formId: source && source.formId,
                        formName: source && source.formName,
                        controlId: source && source.controlId,
                        templateCategory: template.templateCategory,
                    }
                    const icon = DgControl[templateControlType] && DgControl[templateControlType].icon;
                    if (icon) {
                        item.controlIconClass = 'fd-i-Family fd_pc-' + icon;
                    } else {
                        item.controlIconClass = 'f-icon f-icon-paste';
                    }


                    items.push(item);
                }

            });

            subject.next(items);
        }, error => {
            subject.next(null);
        });

        return subject;

    }

    onSelectItem(item: any) {
        item.selected = !item.selected;
    }
    clickCancel() {
        this.closeModal.emit();
    }

    clickConfirm() {

        const checkedItems = this.templateItems.filter(item => item.selected);
        const itemIds = checkedItems.map(item => item.id);

        if (!itemIds.length) {
            this.notifyService.warning('请先选择模板！');
            return;
        }

        this.confirmDelete(itemIds);

    }

    confirmDelete(itemIds: string[]) {
        this.msgService.question('确定删除模板？', () => {

            return this.http.put(this.templateUrl + '/batchDelete', itemIds, this.headerOption).subscribe((data: any) => {
                if (data && data.state) {

                    this.notifyService.success('删除成功');
                    this.submitModal.emit();
                }
                if (data && !data.state) {
                    this.notifyService.warning(data.errorMessage || '删除失败');
                }
            }, () => {
                this.notifyService.warning('删除失败');
            });
        });
    }
}
